package c2c

import (
	"errors"
	"gim-server/apis/ws"
	"gim-server/consts"
	"gim-server/errs"
	"gim-server/model"
	"gim-server/sdk"
	"gim-server/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"time"
)

type DelC2cMsgArgs struct {
	ToUID string `json:"to_uid"`
	MsgID int64  `json:"msg_id"`
}

func delC2cMsg(ctx *gin.Context) {
	var (
		err  error
		args = new(DelC2cMsgArgs)
	)
	if err = ctx.ShouldBindJSON(args); err != nil {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiParamsErr,
			Err:  err,
		})
		return
	}
	db := sdk.DB(ctx)
	err = db.Transaction(func(tx *gorm.DB) error {
		if args.ToUID != "" {
			if err := tx.Model(new(model.TbC2cMsgRecord)).Where(
				"((from_uid = ? and to_uid = ?) or (from_uid = ? and to_uid = ?)) and del_uid = ?",
				ctx.GetString(consts.UID), args.ToUID, args.ToUID, ctx.GetString(consts.UID), "0").UpdateColumn("del_uid", ctx.GetString(consts.UID)).Error; err != nil {
				return err
			}
			if err := tx.Model(new(model.TbC2cMsgRecord)).Where(
				"((from_uid = ? and to_uid = ?) or (from_uid = ? and to_uid = ?)) and del_uid = ?",
				ctx.GetString(consts.UID), args.ToUID, args.ToUID, ctx.GetString(consts.UID), args.ToUID).UpdateColumn("del_uid", "-1").Error; err != nil {
				return err
			}
			if err := tx.Model(new(model.TbConversation)).Where("from_uid = ? and to_uid = ?", ctx.GetString(consts.UID), args.ToUID).UpdateColumn("unread_count", 0).Error; err != nil {
				return err
			}
		}
		if args.MsgID > 0 {
			msg := new(model.TbC2cMsgRecord)
			if err := db.First(msg, "id = ?", args.MsgID).Error; err != nil {
				if !errors.Is(err, gorm.ErrRecordNotFound) {
					return nil
				} else {
					return err
				}
			} else {
				if msg.DelUID == "0" {
					msg.DelUID = ctx.GetString(consts.UID)
				} else {
					msg.DelUID = "-1"
				}
				if err := tx.Save(msg).Error; err != nil {
					return err
				}
			}
			if msg.ToUID == ctx.GetString(consts.UID) && !msg.Readed {
				if err := tx.Model(new(model.TbConversation)).Where("from_uid = ? and to_uid = ?", ctx.GetString(consts.UID), args.ToUID).UpdateColumn("unread_count", gorm.Expr("unread_count - ?", 1)).Error; err != nil {
					return err
				}
			}
		}
		return nil
	})
	if err != nil {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiDbErr,
			Err:  err,
		})
		return
	}
	time.AfterFunc(time.Second, func() {
		//静默修改推送数量
		ws.UpdateBadge(ctx.GetString(consts.UID))
	})
	utils.SUC(ctx, true)
}
